package lhLog

import (
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"os"
	"time"
)

/**
 * Created with Goland.
 * User: 令狐飞侠
 * Date: 2021-12-6
 * Description: logrus
 */
var lhLog *logrus.Logger

func InitLogger() {
	lhLog = logrus.New()
	SetInfoAddFunctionName(false)
	SetInfoOutputFile(false)

}

//不同日志的级别
func LHDebug(msg string, args ...interface{}) {
	lhLog.Debug(msg, args)
}

func LHInfo(msg string, args ...interface{}) {
	lhLog.Info(msg, args)
}

func LHWarn(msg string, args ...interface{}) {
	lhLog.Warn(msg, args)
}

func LHError(msg string, args ...interface{}) {
	lhLog.Error(msg, args)
}

//输出代码文件名
func SetInfoOutputFile(isFile bool) {
	if isFile {
		//log输出到文件
		file, err := os.OpenFile("application.log", os.O_CREATE|os.O_WRONLY, os.ModeAppend)
		if err != nil {
			lhLog.Info("OpenFile fail")
		} else {
			lhLog.Out = file
		}
	} else {
		lhLog.Out = os.Stdout
	}
}

//打开开关，可输出代码文件名、函数名
func SetInfoAddFunctionName(isAdd bool) {
	lhLog.SetReportCaller(isAdd)
}

//使用Fields来进行精细化
func LHKafkaInfo(topic string, msg string, info string) {
	lhLog.Formatter = &logrus.JSONFormatter{}
	lhLog.WithFields(logrus.Fields{
		"topic":   topic,
		"message": msg,
	}).Info(info)
}

// 日志切割
func Rotate() {
	// 日志文件的位置
	path := "/application.log"
	// 日志切割时间间隔
	duration := time.Duration(60 * time.Second)
	rLog, _ := rotatelogs.New(
		"application"+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(path), // // 指向最新的日志文件
		rotatelogs.WithRotationTime(duration))
	lhLog.SetOutput(rLog)
}
